package com.ymt.bpm.web.rest.platform.open;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.util.AES;
import com.ymt.bpm.util.Const;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Properties;

/**
 * Created by Johnny on 2017/10/11.
 */
@RestController
@RequestMapping("/openapi/v1/siteutil")
public class SiteUtilResource {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Environment env;

    private static String[] pwds = {"F7FG2H","F7FGJH","8IMPEY","Q0ZG6J","481YWT","M49L3F","QPNR74","5BN0N8","30UR7H","QX3ENG","IPS3YX","EB3UK5","1BSMEO","3IA4J7","NL4NTV","EU60F7","8ZTSP3","MPDIKS","G0H9Z7","1GHSQV"};


    @PostMapping("/mailto")
    public JSONObject mailto(HttpServletResponse response,
                             @RequestParam(name="name", required = false) String name,
                             @RequestParam(name="email", required = true) String email,
                             @RequestParam(name="company", required = false) String company,
                             @RequestParam(name="message", required = true) String message) {

        if (log.isDebugEnabled()) {
            log.debug("mailto sending mail: from concat "+email);
        }

        response.setHeader("Access-Control-Allow-Origin", env.getProperty("bpmp.site-url-seo", "https://www.bpmyun.cn"));
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        String subject = "[客户咨询]";
        String content = "<b>客户：</b>&nbsp;&nbsp;"+ name+ "&nbsp;("+email+")<br/>" +
                "<b>公司：</b>&nbsp;&nbsp;"+ company + "<br/>" +
                "<b>咨询：</b>&nbsp;&nbsp;"+ message + "<br/>";
        String toMailAddress = env.getProperty("bpmp.mail.address-contact");

        try {
            sendHtmlMail(toMailAddress, subject, content);
        }catch (MessagingException e) {
            e.printStackTrace();
            log.warn("mailto sending mail: from concat "+email+"-"+message);
            return JSONObject.parseObject(Const.AJAX_FALSE);
        }

        return JSONObject.parseObject(Const.AJAX_SUCC);
    }

    @PostMapping("/havetry")
    public JSONObject havetry(HttpServletResponse response,
                             @RequestParam(name="mobile", required = true) String mobile,
                             @RequestParam(name="email", required = true) String email,
                             @RequestParam(name="company", required = false) String company) {

        if (log.isDebugEnabled()) {
            log.debug("havetry sending mail: to concat "+email);
        }
        JSONObject rtn = new JSONObject();

        response.setHeader("Access-Control-Allow-Origin", env.getProperty("bpmp.site-url-seo", "https://www.bpmyun.cn"));
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        int hash = email.hashCode();
        if (hash<0) {
            hash = 0 - hash;
        }
        hash = hash % 20;
        String tryAccount = "test"+String.valueOf(hash);
        String newPwd = pwds[hash];   //hash = 0-19
        String subject = "您的试用帐号[BPM云]";
        String content = "<b>帐号：</b>&nbsp;&nbsp;"+ tryAccount+ "<br/>" +
                "<b>密码：</b>&nbsp;&nbsp;"+ newPwd + "<br/>" +
                "<b>备注：</b>&nbsp;&nbsp;您可能与其他用户共享此试用帐号！<br/>";

        //内部提醒
        String informInternal = env.getProperty("bpmp.mail.address-contact", "info@bpmyun.cn");
        String informInternalSubject = "新试用申请["+company+"]";
        String informInternalContent = "<b>帐号：</b>&nbsp;&nbsp;"+ tryAccount+ "<br/>" +
                "<b>手机：</b>&nbsp;&nbsp;"+ mobile + "<br/>" +
                "<b>邮箱：</b>&nbsp;&nbsp;"+ email + "<br/>";

        try {
            sendHtmlMail(email, subject, content);
            rtn.put("success", true);
        }catch (MessagingException e) {
            e.printStackTrace();
            log.warn("havetry sending mail: to "+email);
        }
        try {
            sendHtmlMail(informInternal, informInternalSubject, informInternalContent);
        }catch (MessagingException e) {
            e.printStackTrace();
            log.warn("havetry sending mail: to "+informInternal);
        }

        return rtn;
    }

    private void sendHtmlMail(String to,
                     String subject,
                     String content) throws MessagingException {

        if (log.isDebugEnabled()) {
            log.debug("sendHtmlMail: to "+to);
        }

        //String protocal = env.getProperty("bpmp.mail.transport-protocol");
        //String smtpPort = env.getProperty("bpmp.mail.smtp-port");
        String smtpServer = env.getProperty("bpmp.mail.smtp-host");
        String fromMailAddress = env.getProperty("bpmp.mail.from-user");
        String password = env.getProperty("bpmp.mail.pwd");
        password = AES.decrypt(password);

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpServer);
        // 创建MIME邮件对象
        // 获得邮件会话对象
        Session session = Session.getDefaultInstance(props,
                new SmtpAuthenticator(fromMailAddress, password));
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromMailAddress));// 发件人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
                to));// 收件人
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());// 发送日期
        BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
        mdp.setContent(content, "text/html;charset=UTF-8");// 设置发送邮件内容为HTML类型,并为中文编码
        Multipart mm = new MimeMultipart();
        mm.addBodyPart(mdp);
        mimeMessage.setContent(mm);
        mimeMessage.saveChanges();
        Transport.send(mimeMessage);// 发送邮件
    }

    class SmtpAuthenticator extends Authenticator {
        String username = null;
        String password = null;

        // SMTP身份验证
        public SmtpAuthenticator(String username, String password) {
            this.username = username;
            this.password = password;
        }

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(this.username, this.password);
        }

    }

    public static void main(String[] args) {
        for (String a : pwds) {
            System.out.println(DigestUtils.sha256Hex(a));
        }
        System.out.println(DigestUtils.sha256Hex("123456"));
    }

}